package com.zzwx.test.dbunit;

import java.io.FileInputStream;
import java.sql.Connection;

import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;

import com.zzwx.test.dbunit.base.DBUnitBase;

/**
 * @author Roger
 * @desc 备份所有数据库所有数据在一个备份文件中
 */
public class DBUnitAll extends DBUnitBase {

	/**
	 * 添加测试数据,并备份数据库所有数据
	 * 
	 * @param fileName
	 *            测试数据文件
	 */
	@SuppressWarnings("deprecation")
	public void setUpBackupAll(String fileName) {
		// JDBC数据库连接
		Connection conn = null;
		// DBUnit数据库连接
		IDatabaseConnection connection = null;
		try {
			conn = getConnection();
			// 获得DB连接
			connection = new DatabaseConnection(conn);
			// 备份数据库测试之前的数据
			backupAll();
			// 准备数据的读入
			IDataSet dataSet = new FlatXmlDataSet(new FileInputStream(
					testDataPath + fileName));
			connection.createDataSet(new String[] {});
			DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeCon();
		}
	}
	
	/**
	 * 备份数据库所有数据
	 */
	public void backupAll(){
		try {
			super.backupData(null, "all_data_back.xml");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 还原数据库到测试之前
	 */
	public void recoverAllData(){
		super.recoverData(file);
	}
}
